#!usr/bin/python
# -*- coding:utf-8 -*-

#接收邮件


from poplib import POP3
import poplib
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr
from KqAuto import *
import threading

userName = 'ch-ch'
passWord = 'UJMujm009'
count = 0
timer = ''
timerCount = 2

def decode_str(s):
    value, charset = decode_header(s)[0]
    # for x in
    if charset:
        value = value.decode(charset)
    return value
def guess_charset(msg):
    charset = msg.get_charset()
    if charset is None:
        content_type = msg.get('Content-Type', '').lower()
        pos = content_type.find('charset=')
        if pos >= 0:
            charset = content_type[pos + 8:].strip()
    return charset

def print_info(msg, indent=0):
    if indent == 0:
        for header in ['From', 'To', 'Subject']:
            value = msg.get(header, '')
            if value:
                if header=='Subject':
                    value = decode_str(value)
                else:
                    hdr, addr = parseaddr(value)
                    name = decode_str(hdr)
                    value = u'%s <%s>' % (name, addr)
            print('%s%s: %s' % ('  ' * indent, header, value))
    if (msg.is_multipart()):
        parts = msg.get_payload()
        for n, part in enumerate(parts):
            # print('%spart %s' % ('  ' * indent, n))
            # print('%s--------------------' % ('  ' * indent))
            print_info(part, indent + 1)
            break
    else:
        content_type = msg.get_content_type()
        if content_type=='text/plain' or content_type=='text/html':
            content = msg.get_payload(decode=True)
            charset = guess_charset(msg)
            if charset:
                content = content.decode(charset)
            # print('%sText: %s' % ('  ' * indent, content + '...'))
            handleContent(content)
        else:
            print('%sAttachment: %s' % ('  ' * indent, content_type))

def handleContent(content):
    print('start handle')
    # print(content)
    global count
    if 'love' in content:
        count = 1
        startGame(userName, passWord)

def init():
    # read
    global userName, passWord

    if len(sys.argv)<3:
        sys.exit(0)
    else:
        userName = sys.argv[1]
        passWord = sys.argv[2]

def login():
    global count, timerCount
    if count != 0:
        # timer = threading.Timer(timerCount, login)
        # timer.start()
        print('return ', count)
        return
    print('--start--', count)
    # count = count + 1
    server = poplib.POP3_SSL('mail.neusoft.com')
    # p = POP3('localhost')
    # server.set_debuglevel(1)
    print(server.getwelcome().decode('utf-8'))

    user = server.user(userName)
    pass_ = server.pass_(passWord)

    resp, mails, octets = server.list()

    index = len(mails)
    # print(mails)
    resp, lines, octets = server.retr(index)
    msg_content = '\r\n'.join(lines).decode('utf-8')
    server.quit()

    try:
        msg = Parser().parsestr(msg_content)
        print_info(msg)
    except:
        pass

    # server.quit()

    print('--over--')

    timer = threading.Timer(timerCount, login)
    timer.start()

if __name__ == '__main__':
    init()
    timer = threading.Timer(timerCount, login)
    timer.start()

